package prog1.helpers;

import prog1.common.Parameters;
import prog1.common.Utils;

import java.security.SecureRandom;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 07/12/13
 *
 * This class represents the random initialization vector.
 * Serialization / De-serialization is done using parameters class.
 */
public class RandomIV {

    private short size;
    private byte[] randomIV;

    public RandomIV() {
    }

    public RandomIV(short size) {
        this.size = size;
    }

    /**
     * Generates random IV
     */
    public void generate() {
        SecureRandom random = new SecureRandom();
        randomIV = new byte[size];
        random.nextBytes(randomIV);
    }

    /**
     * @return random IV (byte array)
     */
    public byte[] getRandomIV() {
        return randomIV;
    }

    /**
     * Serializes this object to parameters
     * @param parameters target object
     */
    public void serialize(Parameters parameters) {
        parameters.add("RANDOM_IV", Arrays.toString(randomIV));
        parameters.add("RANDOM_IV_SIZE", String.valueOf(randomIV.length));
    }

    /**
     * De-serializes this object from parameters
     * @param parameters source object
     */
    public void deserialize(Parameters parameters) {
        String ivStr = parameters.get("RANDOM_IV");
        String sizeStr = parameters.get("RANDOM_IV_SIZE");
        size = Short.parseShort(sizeStr);
        randomIV = Utils.parseByteArray(size, ivStr);
    }
}
